#!/usr/bin/env ruby -wKU
#encoding: UTF-8

module TiebaConfig
  
  class ConfigWriter
    
    def initialize(configXml)
      @configXml = configXml
    end
    
    # user who invoke this method is responsible for keeping novel in @configXml unique  
    # TODO: need to add a few more "\t" text node to make it user readable
    def store novel
      
      builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |x|
        x.novel do
          x.tieba novel.tiebaName
          x.top novel.onTop.to_s
          x.name novel.novelName
          x.author novel.author
        end
      end
      
      File.open(@configXml, "r+") do |file|
        file.flock(File::LOCK_EX)
        file.seek(-10, IO::SEEK_END)
        file.puts builder.doc.root.to_s
        file.puts "</novels>"
      end

      # replace(my_file, /^line2/mi) { |match| "Some nice little sentence"}
 
      # File.open(@configXml, File::RDWR|File::CREAT, 0644) do |f|
        # f.flock(File::LOCK_EX)
        # value = f.read.to_i + 1
        # f.rewind
        # f.write("#{value}\n")
        # f.flush
        # f.truncate(f.pos)
      # end
      
      # xml = Nokogiri::XML(open(@configXml))
      
      # xml.root.add_child(builder.doc.root)
      
      # xml.root.add_child(elm = Nokogiri::XML::Node.new("novel", xml))
#       
      # elm.add_child(tieba = Nokogiri::XML::Node.new("tieba", xml))
      # tieba.add_child(Nokogiri::XML::Text.new(novel.tiebaName, xml))
#       
      # elm.add_child(top = Nokogiri::XML::Node.new("top", xml))
      # top.add_child(Nokogiri::XML::Text.new(novel.onTop.to_s, xml))
#       
      # elm.add_child(name = Nokogiri::XML::Node.new("name", xml))
      # name.add_child(Nokogiri::XML::Text.new(novel.novelName, xml))
#       
      # elm.add_child(author = Nokogiri::XML::Node.new("author", xml))
      # author.add_child(Nokogiri::XML::Text.new(novel.author, xml))
      
      # open(@configXml, "w") do |f|
        # f.flock(File::LOCK_EX)
        # f.write(xml.to_s)
      # end
      
    end
    
    # private 
#     
    # def replace(filepath, regexp, *args, &block)
      # content = File.read(filepath).gsub(regexp, *args, &block)
      # File.open(filepath, 'wb') do |file|
        # file.flock(File::LOCK_EX)
        # file.write(content)
      # end
    # end
    
  end
  
  if __FILE__ == $0

require 'logger'

require 'backend/model/TNovel'
require 'backend/config/ConfigLoader'

$logger = Logger.new('log/rubycrawler.log')

    xmlPath = "config/tieba1.xml"
    # loader = ConfigLoader.new xmlPath
    # loader.load
    
    # novels = Model::Tieba.instance.novels
    novel = Model::TNovel.new
    novel.author='lalala'
    novel.novelName='很懂'
    novel.onTop=true
    novel.tiebaName='tieba'
    
    writer = ConfigWriter.new xmlPath
    writer.store novel
    
  end
  
end